package org.serverct.finalfight.internal.game.basic;

import org.bukkit.*;
import org.bukkit.configuration.file.YamlConfiguration;

public class WorldManager {
    public Location hub;
    public World world;
    public World nether;
    public World end;
    public double initSize;
    public double lessenSpeed;
    public long initTime;
    public boolean autoregenarate;

    public WorldManager(YamlConfiguration yaml) {
        this.hub = new Location(Bukkit.getWorld(yaml.getString("hub.world")),
                yaml.getInt("hub.x"),
                yaml.getInt("hub.y"),
                yaml.getInt("hub.z"));

        this.world = Bukkit.getWorld(yaml.getString("world"));
        this.nether = Bukkit.getWorld(yaml.getString("nether"));
        this.end = Bukkit.getWorld(yaml.getString("end"));

        this.initSize = yaml.getInt("worldsettings.border.init");
        this.lessenSpeed = yaml.getDouble("worldsettings.border.speed");
        this.initTime = yaml.getLong("worldsettings.border.inittime");

        this.autoregenarate = yaml.getBoolean("autoregenarate");

        this.initWorldSettings();
    }

    public void initWorldSettings() {
        this.initWorldSettings(this.world, false);
        this.initWorldSettings(this.nether, true);
        //TODO 末地边界仍待商榷
        this.initWorldSettings(this.end, false);
    }

    public void initWorldSettings(World world, boolean isNether) {
        world.setTime(this.initTime);
        WorldBorder border = world.getWorldBorder();
        border.setCenter(0, 0);
        border.setSize(this.initSize * (isNether ? 8 : 1));
    }

    public void startLessen() {
        this.startLessen(this.world, false);
        this.startLessen(this.nether, true);
        this.startLessen(this.end, false);
    }

    private void startLessen(World world, boolean isNether) {
        WorldBorder border = world.getWorldBorder();
        border.setSize(0, (long) (this.initSize * (isNether ? 8 : 1) / this.lessenSpeed));
    }

    public Location getRandomSpawn() {
        Location loc = new Location(this.world, 0, 0, 0);
        do {
            int x = (int) ((this.initSize * Math.random() / 2.0) * (Math.random() < 0.5 ? -1 : 1));
            int z = (int) ((this.initSize * Math.random() / 2.0) * (Math.random() < 0.5 ? -1 : 1));
            loc.setX(x);
            loc.setZ(z);
            loc.setY(this.world.getHighestBlockYAt(x, z));
        } while (loc.getBlock().isLiquid());
        return loc;
    }
}
